import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_trip/widget/local_nav.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class WebView extends StatefulWidget {
  String url;
  final String statusBarColor;
  final String title;
  final bool hideAppBar;
  final bool backForbid;

  WebView({this.url,
      this.statusBarColor,
      this.title,
      this.hideAppBar,
      this.backForbid = false,//默认值
    });
  @override
  _WebViewState createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
  final webviewReference = FlutterWebviewPlugin();
  StreamSubscription<String> _onUrlChanged;
  StreamSubscription< WebViewStateChanged> _onStateChanged;
  StreamSubscription< WebViewHttpError> _onHttpError;
  bool exiting = false;

  @override
  void initState() {
    super.initState();
    webviewReference.close();
    // 监听 url变化事件
    _onUrlChanged = webviewReference.onUrlChanged.listen((String url){ });
    // 监听 H5页面状态变化
    _onStateChanged = webviewReference.onStateChanged.listen((WebViewStateChanged state){
      switch(state.type){
        case WebViewState.startLoad:
          if(_isToMain(state.url) && !exiting) {//在主页且没有退出
            if(widget.backForbid) {//禁止返回 则加载当前页面
              webviewReference.launch(widget.url);
            }else{
              Navigator.pop(context);
              exiting = true;
            }
          }
          break;
        default:
          break;
      }
    });
    // 监听 加载网页的错误
    _onHttpError = webviewReference.onHttpError.listen((WebViewHttpError error){
      print(error);
    });
  }

  // 判断网址是否在白名单里 fixH5主页面无法返回app 
  _isToMain(String url) {
    bool contain = false;
    for(final value in CATCH_URLS){
      if(url?.endsWith(value) ?? false) {
        contain = true;
        break;
      }
    }
    return contain;
  }

  @override
  void dispose() {
    super.dispose();
    //取消监听
    _onUrlChanged.cancel();
    _onStateChanged.cancel();
    _onHttpError.cancel();
    webviewReference.dispose();//关闭webview
  }

  @override
  Widget build(BuildContext context) {
    //返回按钮颜色
    String statusBarColorStr = widget.statusBarColor ?? 'ffffff';
    Color backButtonColor;
    if (statusBarColorStr == 'ffffff') {
      backButtonColor = Colors.black;
    } else {
      backButtonColor = Colors.white;
    }
    
    return Scaffold(
      body: Column(
        children: <Widget>[
          _appBar(Color(int.parse('0xff'+statusBarColorStr)), backButtonColor),//颜色string转color 先判6/8位
          Expanded(//充满
            child: WebviewScaffold(//H5页面
              url: widget.url,
              withZoom: true,//缩放
              withLocalStorage: true,//本地存储缓存
              hidden: true,//url加载出来之前 是否隐藏
              initialChild: Container(//url加载出来之前 初始化界面
                color: Colors.white,
                child: Center(
                  child: Text('waiting...'),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
  _appBar(Color backgroundColor, Color backButtonColor){
    if(widget.hideAppBar ?? false){
      return Container(
        color: backgroundColor,
        height: 30,
      );
    }
    return Container(
      color: backgroundColor,
      padding: EdgeInsets.fromLTRB(0, 40, 0, 10),
      child: FractionallySizedBox(//根据现有空间，来调整child的尺寸 child就算设置了具体的尺寸数值也不起作用。
        widthFactor: 1,//撑满父布局宽度
        child: Stack(
          children: <Widget>[
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Container(
                margin: EdgeInsets.only(left: 10),
                child: Icon(
                  Icons.close,
                  color: backButtonColor,
                  size: 26,
                ),
              ),
            ),
            // 标题 定位
            Positioned(
              left: 0,
              right: 0,
              child: Center(
                child: Text(
                  widget.title??'',
                  style: TextStyle(color: backButtonColor, fontSize: 20),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}